import os, array, zlib, time
import re
import path
import cPickle
import getpass


blogger = None

file_crc_dic = {}
history_file = "history_blog.ksm"

dirs_to_monitor = ["blogger_dot_com"]

def GetCRC32(filename):
    fileSize = os.stat(filename)[6]
    f = open(filename, "rb")
    v = array.array('B')
    try:
        v.fromfile(f, fileSize)
        i = zlib.crc32(v.tostring())
        return i
    except:
        return None
   
 
def Update():
    global file_crc_dic
    print "updating........"
    try:
        f_history = open(history_file)
        version = cPickle.load(f_history)
        if version == 1.1:
            file_crc_dic = cPickle.load(f_history)
            fo.close()
            for file, crc in file_crc_dic.iteritems():
                print file
                if len(crc) == 2:
                    file_crc_dic[file] = crc
                else:
                    file_crc_dic[file] = (crc,0)
        else:
            print "Version error..."
            sys.exit(1)
    except:
        pass

    deleted_files = []
    for filename, attr in file_crc_dic.iteritems():
        try:
            os.stat(filename)
        except:
            # file not exists -> delete!
            print "%s deleted!" % filename
            deleted_files.append(filename)
            blogger.DeletePost(attr[1])
            
    for deleted_file in deleted_files:
        del file_crc_dic[deleted_file]
    
    for dir_to_monitor in dirs_to_monitor:
        path_to_monitor = path.path(".\\%s"%dir_to_monitor)
        for file in path_to_monitor.files():
            category = []
            content = ""
            if file_crc_dic.has_key(file):
                if GetCRC32(file) != file_crc_dic[file][0]:
                    # updated!
                    print "%s has changed" % file
                    link_to_update = file_crc_dic[file][1]
                    entry_to_update = blogger.GetPost(link_to_update)
                    if not entry_to_update:
                        continue

                    f_temp = open(file)
                    title = f_temp.readline()

                    for line in f_temp:
                        if line.startswith("label:"):
                            line = line[6:]
                            category_temp = line.split(",")
                            for category_item in category_temp:
                                category.append(category_item.decode("euc-kr").strip())
                            continue
                        content += line
                        
                    blogger.UpdatePost(entry_to_update, title, content, category)
                    file_crc_dic[file] = (GetCRC32(file), entry_to_update.link[1].href)
            else:
                # a file has been created
                print "%s has created" % file
                f_temp = open(file)
                title = f_temp.readline()
                for line in f_temp:
                    if line.startswith("label:"):
                        line = line[6:]
                        category_temp = line.split(",")
                        for category_item in category_temp:
                            category.append(category_item.decode("euc-kr").strip())
                        continue
                    content += line

                title = title.decode("euc-kr")
                content = content.decode("euc-kr")

                public_post = blogger.CreatePost(title,
                  content,
                  "Post author", False, category)
                file_crc_dic[file] = (GetCRC32(file), public_post.link[1].href)

    fo = open( history_file, "wb")
    version = 1.1
    cPickle.dump( version, fo)
    cPickle.dump( file_crc_dic, fo )
    fo.close()
   
def InitBlogger(password):
    global blogger
    email = 'nemonemo@gmail.com'
    blogger = BloggerExample(email, password)
"""
if __name__ == "__main__":
    InitBlogger()
    while True:
        /getp
        time.sleep(1)
"""
